﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SubtitleDownloader
{
	public class VideoItem
	{
		public string FileName { get; private set; }
		public string OriginalName { get; private set; }

		public bool HaveSubtitles
		{
			get
			{
				return
					File.Exists(Path.ChangeExtension(FileName, ".srt")) ||
					File.Exists(Path.ChangeExtension(FileName, ".sub"));
			}
		}

		public string Name { get; private set; }
		public int Season { get; private set; }
		public int Episode { get; private set; }
		public int Episode2 { get; private set; }
		public string ExtraInfo { get; private set; }

		public VideoItem(string filename, string name = null)
		{
			if (filename != null) {
				FileName = filename;
				OriginalName = name ?? Path.GetFileName(filename);
				ParseName();
			}
		}

		private void ParseName()
		{
			var match = Regex.Match(OriginalName,
				@"^(?:.*\\)?(?<series>[^\\]+?)[ _.\-\[]+(?:[s]?(?<season>\d+)[ _.\-\[\]]*[ex](?<episode>\d+)|(?:\#|\-\s)(?<season>(?!(?:\d{4}.\d{2}.\d{2}|\d{2}.\d{2}.\d{4}))\d+)\.(?<episode>\d+))(?:[ _.+-]+(?:[s]?\k<season>[ _.\-\[\]]*[ex](?<episode2>\d+)|(?:\#|\-\s)\k<season>\.(?<episode2>\d+))|(?:[ _.+-]*[ex+-]+(?<episode2>\d+)))*[ _.\-\[\]]*(?<title>(?![^\\].*?(?<!the)[ .(-]sample[ .)-]).*?)\.(?<ext>[^.]*)$",
				RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
			if (match != null) {
				int episode, episode2, season;
				int.TryParse(match.Groups["season"].Value, out season);
				int.TryParse(match.Groups["episode"].Value, out episode);
				int.TryParse(match.Groups["episode2"].Value, out episode2);
				
				Name = ApplyTranslators(match.Groups["series"].Value.CleanString().ToLower());
				ExtraInfo = match.Groups["title"].Value.CleanString().ToLower();
				Season = season;
				Episode = episode;
				Episode2 = episode2;
			}
		}

		private string ApplyTranslators(string str)
		{
			foreach (var key in Data.Instance.CustomNameTranslator.Keys)
				str = str.Replace(key, Data.Instance.CustomNameTranslator[key]);
			return str;
		}
	}
}
